package com.ff.discounts.component.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.ff.discounts.entity.response.onSuccess
import com.ff.discounts.library.log.HiLog
import com.ff.discounts.model.BaseViewModel
import com.ff.discounts.repository.DefaultNetworkRepository
import com.ff.discounts.util.PreferenceUtil
import kotlinx.coroutines.launch

/**
 *
 * @author: fufang
 * @date: 2023/10/24
 */
class LoginViewModel : BaseViewModel() {
    private var param: LoginRequest = LoginRequest()

    //成功
    private val _success = MutableLiveData<String>()
    val success: LiveData<String> = _success

    /**
     * 验证码登录
     */
    fun codeLogin(mobile: String, code: String) {
        param.mobile = mobile
        param.code = code
        login(param)
    }
    /**
     * 密码登录
     */
    fun passwordLogin(mobile: String, password: String) {
        param.account = mobile
        param.password = password
        passwordLogin(param)
    }


    /**
     * 发送验证码
     */
    fun getCode(mobile: String) {
        param.mobile = mobile
        viewModelScope.launch(coroutineExceptionHandler) {
            DefaultNetworkRepository.getCode(param).onSuccess(viewModel){
                HiLog.d(it)
            }
        }

    }

    /**
     *  验证码登录
     */
    private fun login(data: LoginRequest) {
        viewModelScope.launch(coroutineExceptionHandler) {
            DefaultNetworkRepository.codeLogin(data).onSuccess(viewModel) {
                HiLog.d(data)
            }
        }
    }
    /**
     * 用户名和密码
     */
    private fun passwordLogin(data: LoginRequest) {
        viewModelScope.launch(coroutineExceptionHandler) {
            DefaultNetworkRepository.passwordLogin(data).onSuccess(viewModel) {
                if (it != null) {
                    PreferenceUtil.setToken(it!!.token)
                    _success.value = it.token
                }
            }
        }
    }
}
